function createHashHistory(){
  let globalHistory = window.history;
  let stack = [];
  let index = 1;
  let action = 'POP';
  let state;
  let listeners = [];

  function listen(listener){
    listeners.push(listener);
    return () => {
      listeners = listeners.filter(item => item !== listener);
    }
  };
  
  function push(pathname, nextState){
    action = "PUSH";
    if(typeof pathname === "object"){
      state = pathname.state;
      pathname = pathname.pathname;
    }else{
      state = nextState;
    }
    window.location.hash = pathname;
  };
  
  function go(n){
    action = "POP";
    index += n;
    let nextLocation = stack[index];
    state = nextLocation.state;
    window.location.hash = nextLocation.pathname;
  };
  function goBack(){
    globalHistory.go(-1);
  }
  function goForward(){
    globalHistory.go(1);
  };
  function handleHashChange(){
    // 获取最新的写在hash值中的路径名
    const pathname = window.location.hash.slice(1);
    history.action = action;
    const location= { pathname, state };
    history.location= location;
    if(action === 'PUSH'){
      stack[++index] = location;
    };
    listeners.forEach(listener => {
      listener({action, location})
    })
  };
  window.addEventListener('hashchange', handleHashChange);
  const history = {
    action: 'POP',
    go,
    goBack,
    goForward,
    push,
    listen,
    location: {
      // pathname: window.location.hash ? window.location.hash.slice(1): "/",
      state: undefined,
      pathname: undefined,
    }
  }
  if(window.location.hash){
    action = "PUSH";
    handleHashChange();
  }else{
    window.location.hash = "/";
  }
  return history;
}

export default createHashHistory;